package com.hzjq.core.impl

import com.hzjq.core.ErrorCode
import com.hzjq.core.bean.CapProgressEntity
import com.hzjq.core.bean.ChargeProgressEntity
import com.hzjq.core.bean.ErrorReadCapEntity
import com.hzjq.core.callback.Callback
import com.hzjq.core.callback.ProgressCallback
import com.hzjq.core.loader.OnChargeLoader
import com.hzjq.core.work.Works
import com.hzjq.core.worker.*
import io.reactivex.functions.Consumer

class ChargeImpl : OnChargeLoader {

    private var works: Works? = null
    private var closeWork: Works? = null

    override fun onCharge(
        callback: ProgressCallback<ChargeProgressEntity>,
        errorCallback: Consumer<ErrorReadCapEntity>
    ) {
        cancel()
        works = Works.Builder.newBuilder()
            .addWork(ChargeWork(callback))
            .addWork(ChargeQueryWork(callback, errorCallback))
            .addWork(ElectricVoltageWork(callback as ProgressCallback<CapProgressEntity>))
            .build()
            .queue()
    }

    override fun onCloseElectric(callback: Callback<Boolean>) {
        CheckerImpl().setCallback(Consumer {
            if (it) {
                works?.onDestroy()
                closeWork = Works.Builder.newBuilder()
                    .addWork(CloseChargeWork(callback))
                    .addWork(BackWork(callback))
                    .build()
                    .queue()
            } else {
                callback.onError(ErrorCode.getErrorResult(103))
            }
        }).start()
    }


    override fun cancel() {
        works?.onDestroy()
        closeWork?.onDestroy()
    }
}